//
//  NewCameraViewController.m
//  Logistics
//
//  Created by 刘峰 on 2018/1/11.
//  Copyright © 2018年 com.Logistics. All rights reserved.
//

#import "NewCameraViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "PhotoBrowerManager.h"

@interface NewCameraViewController ()

{
    BOOL isUsingFrontFacingCamera;
    AVAuthorizationStatus status;
}
@property (nonatomic, strong) AVCaptureSession *captureSession; // 会话管理类

@property (nonatomic, strong) AVCaptureDeviceInput *deviceInput; // 捕捉设备输入

@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer; // 预览层

@property (nonatomic, strong) AVCaptureStillImageOutput *stillImageOutput; // 照片输出流

@property (weak, nonatomic) IBOutlet UIView *imagePreview;
@property (weak, nonatomic) IBOutlet UIImageView *photoImage;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayout;

@end

@implementation NewCameraViewController

- (IBAction)getBack:(id)sender {
    [self.captureSession stopRunning];
    [self dismissALLViewController];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (IS_IPHONEX) {
        _topLayout.constant = 35;
    }
    self.navigationController.navigationBarHidden = YES;
    
    status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    WEAKSELF
    switch (status) {
        case AVAuthorizationStatusNotDetermined:{
            // 许可对话没有出现，发起授权许可
            
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    //第一次用户接受
                    [weakSelf configureSession];
                }else{
                    // 用户拒绝
                    [[LFAlertBox backgroundAlert] showAlertTitle:@{@"text":@"提示"} content:@{@"text":@"拒绝授权将无法使用相机"} cancleBtn:nil sureBtn:@{@"text":@"狠心拒绝"} completion:^(NSInteger index) {
                        [weakSelf dismissALLViewController];
                    }];

                }
            }];
        }
            break;
            
        case AVAuthorizationStatusAuthorized:{
            // 已经开启授权，可继续
            [self configureSession];
        }
            break;

        default:{
            // 用户明确地拒绝授权，或者相机设备无法访问
            [[LFAlertBox backgroundAlert] showAlertTitle:@"提示" content:@"请前往系统【设置】->【隐私】->【相机】->【龟米】，开启相机访问权限" cancleText:@"取消" sureText:@"设置" completion:^(NSInteger index) {
                if (index == 0) {
                    [weakSelf dismissALLViewController];
                }else {
                    [NSObject openSystemURL:UIApplicationOpenSettingsURLString];
                }
            }];
        }
            break;
    }
    
}

- (void)configureSession {
    _captureSession = [[AVCaptureSession alloc] init];
    _captureSession.sessionPreset = AVCaptureSessionPresetHigh;
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    NSError *error;
    _deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error: &error];
    if (_deviceInput) {
        if ([self.captureSession canAddInput:_deviceInput]) {
            [self.captureSession addInput:_deviceInput];
        }
    }

    _stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    [_stillImageOutput setOutputSettings:@{AVVideoCodecKey :AVVideoCodecJPEG}];
    if (_stillImageOutput) {
        if ([self.captureSession canAddOutput:_stillImageOutput]) {
            [self.captureSession addOutput:_stillImageOutput];
        }
    }
    
    _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _previewLayer.frame = CGRectMake(0, 0, KscreenWidth, KscreenHeight);
    [self.view.layer insertSublayer:_previewLayer atIndex:0];
    
    [self.captureSession startRunning];
}

// 切换摄像头
- (IBAction)SwitchingCamera:(id)sender {
    AVCaptureDevicePosition desiredPosition;
    if (isUsingFrontFacingCamera){
        desiredPosition = AVCaptureDevicePositionBack;
    }else{
        desiredPosition = AVCaptureDevicePositionFront;
    }
    
    for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
        if ([d position] == desiredPosition) {
            [self.previewLayer.session beginConfiguration];
            AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil];
            for (AVCaptureInput *oldInput in self.previewLayer.session.inputs) {
                [[self.previewLayer session] removeInput:oldInput];
            }
            [self.previewLayer.session addInput:input];
            [self.previewLayer.session commitConfiguration];
            break;
        }
    }
    
    isUsingFrontFacingCamera = !isUsingFrontFacingCamera;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 拍照
- (IBAction)takingPictures:(id)sender {
    if (status == AVAuthorizationStatusAuthorized) {
        
        AVCaptureConnection *connection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
        if (connection.isVideoOrientationSupported) {
            connection.videoOrientation = AVCaptureVideoOrientationPortrait;
        }
        
        [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef  _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
            if (imageDataSampleBuffer != NULL) {
                _imagePreview.hidden = NO;
                NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                _photoImage.image = [UIImage imageWithData:imageData];
            }
        }];
        
    }
}

// 重拍
- (IBAction)aRemakeAction:(id)sender {
    _imagePreview.hidden = YES;
}

// 完成拍照
- (IBAction)finishTakePicture:(UIButton *)sender {
    sender.enabled = NO;
    if (self.presentingViewController) {
        [self dismissALLViewController];
    }else {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(didFinishPackingMediaWithImage:)]) {
        [self.delegate didFinishPackingMediaWithImage:_photoImage.image];
    }else {
        [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationDidFinishIMAGE object:self userInfo:@{@"images":@[_photoImage.image]}];
    }
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}


@end
